<template>
  <XenPageLayout
    :title="title"
    title-align="left"
    :navbar-bg-color="themeConfig.primaryColor"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    :contentStyle="gradientStyle"
  >
    <!-- 主体内容 -->
    <view class="list-container">
      <!-- 搜索区域 -->
      <view class="search-section">
        <view class="search-bar-container">
          <view class="search-bar">
            <!-- 搜索图标插槽 -->
            <slot name="search-icon">
              <!-- 默认无图标 -->
            </slot>
            <view class="search-input" @click="openFilterDrawer">
              {{ searchPlaceholder || "点击筛选信息" }}
            </view>
          </view>
          <view
            class="add-btn"
            @click="handleAdd"
            v-if="showAddButtonWithPermission"
          >
            <!-- 添加按钮图标插槽 -->
            <slot name="add-icon">
              <!-- 默认无图标 -->
            </slot>
            <text class="add-text">{{ addButtonText || "新增" }}</text>
          </view>
        </view>
      </view>

      <!-- 列表内容区域 -->
      <view class="list-section">
        <!-- 加载状态 -->
        <view v-if="finalLoading" class="loading-container">
          <!-- 加载图标插槽 -->
          <slot name="loading-icon">
            <!-- 默认无图标 -->
          </slot>
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 列表内容 -->
        <view v-else-if="dataList.length > 0" class="list-container">
          <!-- 聊天列表样式 -->
          <template v-if="chatListStyle">
            <view
              v-for="(item, index) in dataList"
              :key="index"
              class="chat-item"
              @click="handleView(item)"
            >
              <view class="chat-avatar">
                <!-- 自定义头像图标插槽 -->
                <slot
                  name="avatar-icon"
                  :item="item"
                  v-if="hasCustomAvatarSlot"
                >
                  <!-- 默认无图标 -->
                </slot>
                <!-- 默认头像图标 -->
                <view v-else class="default-chat-avatar">
                  <uni-icons
                    type="chatbubble"
                    size="20"
                    color="#ffffff"
                  ></uni-icons>
                </view>
              </view>
              <view class="chat-content">
                <view class="chat-main">
                  <text
                    class="chat-title"
                    :class="{ 'unread-title': item.Status === '未读' }"
                    v-if="getItemTitle(item)"
                  >
                    {{ getItemTitle(item) }}
                  </text>
                  <text class="chat-time">{{
                    formatChatTime(item[timeField])
                  }}</text>
                </view>
                <text class="chat-subtitle" v-if="getItemSubtitle(item)">
                  {{ getItemSubtitle(item) }}
                </text>
              </view>
            </view>
          </template>

          <!-- 原有卡片样式 -->
          <template v-else>
            <view
              v-for="(item, index) in dataList"
              :key="index"
              class="data-card"
            >
              <view
                class="card-header"
                :class="{ 'no-avatar': !hasCustomAvatarSlot }"
                v-if="
                  getItemTitle(item) ||
                  getItemSubtitle(item) ||
                  hasCustomAvatarSlot
                "
              >
                <view class="item-avatar" v-if="hasCustomAvatarSlot">
                  <!-- 头像图标插槽 -->
                  <slot name="avatar-icon" :item="item">
                    <!-- 默认无图标 -->
                  </slot>
                </view>
                <view
                  class="item-info"
                  v-if="getItemTitle(item) || getItemSubtitle(item)"
                >
                  <text class="item-title" v-if="getItemTitle(item)">{{
                    getItemTitle(item)
                  }}</text>
                  <text class="item-subtitle" v-if="getItemSubtitle(item)">{{
                    getItemSubtitle(item)
                  }}</text>
                </view>
              </view>

              <view class="card-content">
                <view
                  v-for="field in visibleFields"
                  :key="field.key"
                  class="info-item"
                >
                  <text class="label">{{ field.label }}：</text>
                  <!-- 徽章样式字段 -->
                  <view v-if="field.type === 'badge'" class="value">
                    <view
                      class="status-badge"
                      :class="getBadgeClass(item, field)"
                    >
                      {{ getFieldValue(item, field) }}
                    </view>
                  </view>
                  <!-- 普通文本字段 -->
                  <text v-else class="value">{{
                    getFieldValue(item, field)
                  }}</text>
                </view>
              </view>

              <view class="card-footer">
                <view class="action-buttons">
                  <view
                    v-for="action in getFilteredActionsForItem(item)"
                    :key="action.key"
                    class="action-btn"
                    :class="action.class"
                    @click="handleAction(action.key, item)"
                  >
                    <!-- 操作按钮图标插槽 -->
                    <slot :name="`action-icon-${action.key}`" :action="action">
                      <!-- 默认无图标 -->
                    </slot>
                    <text>{{ action.label }}</text>
                  </view>
                </view>
              </view>
            </view>
          </template>
        </view>

        <!-- 空状态 -->
        <view v-else class="empty-container">
          <!-- 空状态图标插槽 -->
          <slot name="empty-icon">
            <!-- 默认无图标 -->
          </slot>
          <text class="empty-text">{{ emptyText || "暂无数据" }}</text>
          <text class="empty-desc">{{ emptyDesc || "" }}</text>
        </view>
      </view>
    </view>

    <!-- 抽屉式搜索面板 -->
    <XenFilterDrawer
      ref="filterDrawerRef"
      @reset="resetFilterForm"
      @apply="applyFilter"
      @close="onFilterDrawerClose"
    >
      <template v-for="filter in filterFields" :key="filter.key">
        <XenFilterFormItem
          :label="filter.label"
          :placeholder="filter.placeholder"
          v-model="filterForm[filter.key]"
        >
          <!-- 不同类型的筛选字段插槽 -->
          <template v-if="filter.type === 'selector'">
            <!-- #ifdef APP-PLUS -->
            <XenAppPicker
              mode="selector"
              :range="filter.options"
              :value="filterForm[filter.key]"
              :placeholder="filter.placeholder"
              @change="
                (value: any) => handleAppSelectorChange(filter.key, value)
              "
            />
            <!-- #endif -->
            <!-- #ifndef APP-PLUS -->
            <picker
              mode="selector"
              :range="filter.options"
              @change="
                (e: any) =>
                  handleSelectorChange(filter.key, e, filter.options || [])
              "
              class="form-picker"
            >
              <view class="picker-content">
                <text class="picker-text">{{
                  filterForm[filter.key] || filter.placeholder
                }}</text>
                <uni-icons type="down" size="14" color="#999"></uni-icons>
              </view>
            </picker>
            <!-- #endif -->
          </template>

          <template v-else-if="filter.type === 'date'">
            <!-- #ifdef APP-PLUS -->
            <XenAppPicker
              mode="date"
              :value="filterForm[filter.key]"
              :placeholder="filter.placeholder"
              @change="(value: any) => handleAppDateChange(filter.key, value)"
            />
            <!-- #endif -->
            <!-- #ifndef APP-PLUS -->
            <picker
              mode="date"
              :value="filterForm[filter.key]"
              @change="(e: any) => handleDateChange(filter.key, e)"
              class="form-picker"
            >
              <view class="picker-value">{{
                filterForm[filter.key] || filter.placeholder
              }}</view>
            </picker>
            <!-- #endif -->
          </template>

          <!-- 日期范围选择器 -->
          <template v-else-if="filter.type === 'daterange'">
            <uni-datetime-picker
              v-model="filterForm[filter.key]"
              type="daterange"
              :placeholder="filter.placeholder"
              @change="(e: any) => handleDateRangeChange(filter.key, e)"
              @show="handleDatePickerShow"
              @hide="handleDatePickerHide"
              @confirm="handleDatePickerHide"
              @cancel="handleDatePickerHide"
              @maskClick="handleDatePickerHide"
              class="form-picker daterange-picker"
            />
          </template>

          <template v-else-if="filter.type === 'time'">
            <picker
              mode="time"
              :value="filterForm[filter.key]"
              @change="(e: any) => handleTimeChange(filter.key, e)"
              class="form-picker"
            >
              <view class="picker-value">{{
                filterForm[filter.key] || filter.placeholder
              }}</view>
            </picker>
          </template>

          <!-- 部门选择器 -->
          <template v-else-if="filter.type === 'department-picker'">
            <XenDepartmentPicker
              v-model="filterForm[filter.key]"
              :placeholder="filter.placeholder"
              :popup-title="filter.popupTitle || '选择部门'"
              :department-data="filter.departmentData || []"
              @change="
                (value: string) => handleDepartmentChange(filter.key, value)
              "
              @popup-open="handleDepartmentPickerShow"
              @popup-close="handleDepartmentPickerHide"
            />
          </template>

          <!-- 默认处理：文本输入框 -->
          <template v-else>
            <view class="uni-input-wrapper">
              <input
                class="uni-input"
                type="text"
                :value="filterForm[filter.key]"
                :placeholder="filter.placeholder"
                @input="(e: any) => handleTextInput(filter.key, e)"
              />
            </view>
          </template>
        </XenFilterFormItem>
      </template>
    </XenFilterDrawer>
  </XenPageLayout>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  computed,
  onMounted,
  watch,
  useSlots,
  type PropType,
} from "vue";
import { onShow as uniOnShow } from "@dcloudio/uni-app";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenFilterDrawer from "@/components/XenFilterDrawer.vue";
import XenFilterFormItem from "@/components/XenFilterFormItem.vue";
import XenDepartmentPicker from "@/components/XenDepartmentPicker.vue";
// #ifdef APP-PLUS
import XenAppPicker from "@/components/XenAppPicker.vue";
// #endif
import { auth } from "@/utils/authFunction";

// 定义字段类型接口
interface FieldConfig {
  key: string;
  label: string;
  placeholder?: string;
  type?: string;
  options?: any[];
  required?: boolean;
  formatter?: (value: any) => string;
  badgeConfig?: {
    colorMap?: Record<string, string>;
    defaultColor?: string;
    prefix?: string;
  };
  // 部门选择器相关属性
  popupTitle?: string;
  departmentData?: any[];
}

// 定义操作类型接口
interface ActionConfig {
  key: string;
  label: string;
  icon: string;
  color: string;
  class: string;
}

// 定义主题配置
interface ThemeConfig {
  primaryColor: string;
  secondaryColor: string;
  gradientStart?: string;
  gradientEnd?: string;
}

// 组件属性定义
const props = defineProps({
  // 页面标题
  title: {
    type: String,
    default: "数据管理",
  },
  // 数据列表
  dataList: {
    type: Array as PropType<any[]>,
    default: () => [],
  },
  // 显示的字段配置
  visibleFields: {
    type: Array as PropType<FieldConfig[]>,
    default: () => [],
  },
  // 筛选字段配置
  filterFields: {
    type: Array as PropType<FieldConfig[]>,
    default: () => [],
  },
  // 列表操作按钮配置
  actions: {
    type: Array as PropType<ActionConfig[]>,
    default: () => [
      {
        key: "delete",
        label: "删除",
        icon: "trash",
        color: "#FF5252",
        class: "delete-btn",
      },
      {
        key: "edit",
        label: "编辑",
        icon: "compose",
        color: "#4CAF50",
        class: "edit-btn",
      },
      {
        key: "view",
        label: "查看",
        icon: "eye",
        color: "#7881de",
        class: "view-btn",
      },
    ],
  },
  // 主题配置
  themeConfig: {
    type: Object as PropType<ThemeConfig>,
    default: () => ({
      primaryColor: "#7881de",
      secondaryColor: "#764ba2",
      gradientStart: "#667eea",
      gradientEnd: "#764ba2",
    }),
  },
  // 头像图标 - 为了保持向后兼容，保留此属性但默认不使用
  avatarIcon: {
    type: String,
    default: "",
  },
  // 是否显示添加按钮
  showAddButton: {
    type: Boolean,
    default: true,
  },
  // 是否显示编辑按钮
  showEditButton: {
    type: Boolean,
    default: true,
  },
  // 是否显示详情按钮
  showDetailButton: {
    type: Boolean,
    default: true,
  },
  // 是否显示删除按钮
  showDeleteButton: {
    type: Boolean,
    default: true,
  },
  // 搜索框占位符
  searchPlaceholder: String,
  // 空状态文本
  emptyText: String,
  // 空状态描述
  emptyDesc: String,
  // 详情页路径
  detailPagePath: String,
  // 编辑页路径
  editPagePath: String,
  // 创建页路径
  createPagePath: String,
  // 标题字段
  titleField: {
    type: String,
    default: "name",
  },
  // 子标题字段
  subtitleField: {
    type: String,
    default: "company",
  },
  // 外部控制的加载状态
  loading: {
    type: Boolean,
    default: false,
  },
  // 是否启用自动刷新（页面显示时自动触发refresh事件）
  enableAutoRefresh: {
    type: Boolean,
    default: true,
  },
  // 初始筛选值
  initialFilterValues: {
    type: Object as PropType<Record<string, any>>,
    default: () => ({}),
  },
  // 权限控制相关
  // 权限模块名（自动生成API路径）或完整的API路径（手动指定）
  permissionModule: {
    type: String,
    default: "",
  },
  // 新增权限的API路径（手动指定时使用，优先级高于permissionModule）
  addPermission: {
    type: String,
    default: "",
  },
  // 编辑权限的API路径（手动指定时使用，优先级高于permissionModule）
  editPermission: {
    type: String,
    default: "",
  },
  // 详情权限的API路径（手动指定时使用，优先级高于permissionModule）
  detailPermission: {
    type: String,
    default: "",
  },
  // 删除权限的API路径（手动指定时使用，优先级高于permissionModule）
  deletePermission: {
    type: String,
    default: "",
  },
  // 是否使用聊天列表样式（简洁样式）
  chatListStyle: {
    type: Boolean,
    default: false,
  },
  // 时间字段名（用于聊天列表样式）
  timeField: {
    type: String,
    default: "SendTime",
  },
  // 添加按钮文本
  addButtonText: {
    type: String,
    default: "新增",
  },
  // 静默刷新配置
  enableSilentRefresh: {
    type: Boolean,
    default: true,
  },
  // 静默刷新的数据获取函数
  silentRefreshFn: {
    type: Function as PropType<() => Promise<any[]>>,
    default: null,
  },
});

// 事件
const emits = defineEmits([
  "add",
  "edit",
  "delete",
  "view",
  "filter",
  "search",
  "refresh",
  "action",
  "silent-refresh", // 新增静默刷新事件
]);

const filterForm = reactive<Record<string, any>>({
  ...props.initialFilterValues,
});

// 监听初始筛选值的变化，同步更新 filterForm
watch(
  () => props.initialFilterValues,
  (newValues) => {
    Object.keys(filterForm).forEach((key) => {
      delete filterForm[key];
    });
    Object.assign(filterForm, newValues);
  },
  { deep: true },
);

// 内部加载状态（用于筛选等操作）
const internalLoading = ref(false);

// 计算最终的加载状态（外部loading优先，否则使用内部loading）
const finalLoading = computed(() => {
  return props.loading || internalLoading.value;
});

// 静默刷新相关状态
const needsSilentRefresh = ref(false);
const lastNavigationTime = ref(0);

// 静默刷新函数
const performSilentRefresh = async () => {
  if (!props.enableSilentRefresh || !props.silentRefreshFn) {
    return;
  }

  try {
    const newData = await props.silentRefreshFn();
    if (newData && Array.isArray(newData)) {
      emits("silent-refresh", newData);
    }
  } catch (error) {
    console.warn("静默刷新失败:", error);
    // 静默刷新失败时不显示错误提示，避免打扰用户
  }
};

// 检查是否需要静默刷新
const checkSilentRefresh = () => {
  if (!props.enableSilentRefresh) {
    return;
  }

  const now = Date.now();
  const timeSinceNavigation = now - lastNavigationTime.value;

  // 如果是从其他页面返回（距离上次导航时间超过1秒），则进行静默刷新
  if (timeSinceNavigation > 1000 || needsSilentRefresh.value) {
    needsSilentRefresh.value = false;
    performSilentRefresh();
  }
};

// 权限检查函数
const hasPermission = (permission: string): boolean => {
  if (!permission) return true; // 如果没有设置权限，则默认有权限
  return auth(permission);
};

// 生成权限路径的函数
const getPermissionPath = (action: string, manualPath?: string): string => {
  // 如果手动指定了路径，优先使用手动路径
  if (manualPath) return manualPath;

  // 如果没有设置权限模块，返回空字符串
  if (!props.permissionModule) return "";

  // 根据操作类型自动生成API路径
  switch (action) {
    case "add":
      return `/api/${props.permissionModule}/Add`;
    case "edit":
      return `/api/${props.permissionModule}/Edit`;
    case "detail":
      return `/api/${props.permissionModule}/{id}`;
    case "delete":
      return `/api/${props.permissionModule}/BatchDelete`;
    default:
      return "";
  }
};

// 计算是否显示新增按钮（结合手动控制和权限控制）
const showAddButtonWithPermission = computed(() => {
  const addPath = getPermissionPath("add", props.addPermission);
  return props.showAddButton && hasPermission(addPath);
});

// 计算过滤后的操作按钮（根据手动显示控制和权限控制）
const filteredActions = computed(() => {
  return props.actions.filter((action) => {
    switch (action.key) {
      case "edit":
        const editPath = getPermissionPath("edit", props.editPermission);
        return props.showEditButton && hasPermission(editPath);
      case "view":
        const detailPath = getPermissionPath("detail", props.detailPermission);
        return props.showDetailButton && hasPermission(detailPath);
      case "delete":
        const deletePath = getPermissionPath("delete", props.deletePermission);
        return props.showDeleteButton && hasPermission(deletePath);
      default:
        return true; // 其他自定义操作默认显示
    }
  });
});

// 为每个item动态过滤操作按钮（结合权限控制和业务状态控制）
const getFilteredActionsForItem = (item: any) => {
  return props.actions.filter((action) => {
    switch (action.key) {
      case "edit":
        const editPath = getPermissionPath("edit", props.editPermission);
        // 编辑按钮需要权限且BillStatus为'草稿'（支持数字0或文字"草稿"）
        return (
          props.showEditButton &&
          hasPermission(editPath) &&
          (item.BillStatus === "草稿" || item.BillStatus === 0)
        );
      case "view":
        const detailPath = getPermissionPath("detail", props.detailPermission);
        return props.showDetailButton && hasPermission(detailPath);
      case "delete":
        const deletePath = getPermissionPath("delete", props.deletePermission);
        // 删除按钮需要权限且BillStatus为'草稿'（支持数字0或文字"草稿"）
        return (
          props.showDeleteButton &&
          hasPermission(deletePath) &&
          (item.BillStatus === "草稿" || item.BillStatus === 0)
        );
      default:
        return true; // 其他自定义操作默认显示
    }
  });
};

// 抽屉引用
const filterDrawerRef = ref();
// 过滤表单

// 计算样式
const gradientStyle = computed(() => {
  return `background: linear-gradient(135deg, ${
    props.themeConfig.gradientStart || props.themeConfig.primaryColor
  } 0%, ${
    props.themeConfig.gradientEnd || props.themeConfig.secondaryColor
  } 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;`;
});

// 获取插槽
const slots = useSlots();

// 检查是否有自定义头像插槽
const hasCustomAvatarSlot = computed(() => {
  return !!slots["avatar-icon"];
});

// 获取项目标题
const getItemTitle = (item: any) => {
  const title = item[props.titleField];
  return title && title.trim() ? title : null;
};

// 获取项目副标题
const getItemSubtitle = (item: any) => {
  const subtitle = item[props.subtitleField];
  return subtitle && subtitle.trim() ? subtitle : null;
};

// 格式化时间为聊天列表样式
const formatChatTime = (time: any) => {
  if (!time) return "";

  const date = new Date(time);
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
  const messageDate = new Date(
    date.getFullYear(),
    date.getMonth(),
    date.getDate(),
  );

  if (messageDate.getTime() === today.getTime()) {
    // 今天：显示时间
    return date.toLocaleTimeString("zh-CN", {
      hour: "2-digit",
      minute: "2-digit",
    });
  } else if (messageDate.getTime() === yesterday.getTime()) {
    // 昨天
    return "昨天";
  } else if (now.getTime() - date.getTime() < 7 * 24 * 60 * 60 * 1000) {
    // 一周内：显示星期
    const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    return weekdays[date.getDay()];
  } else {
    // 更早：显示月日
    return date.toLocaleDateString("zh-CN", {
      month: "2-digit",
      day: "2-digit",
    });
  }
};

// 获取字段值
const getFieldValue = (item: any, field: FieldConfig) => {
  const value = item[field.key];
  if (field.formatter) {
    return field.formatter(value);
  }
  return value === undefined || value === null ? "无" : value;
};

// 获取徽章样式类
const getBadgeClass = (item: any, field: FieldConfig) => {
  const value = item[field.key];
  const badgeConfig = field.badgeConfig;

  if (!badgeConfig) {
    return "badge-default";
  }

  const prefix = badgeConfig.prefix || "badge-";
  const colorMap = badgeConfig.colorMap || {};
  const defaultColor = badgeConfig.defaultColor || "gray";

  // 根据配置的颜色映射生成样式类名
  const color = colorMap[value] || defaultColor;
  return `${prefix}${color}`;
};

// 打开筛选抽屉
const openFilterDrawer = () => {
  filterDrawerRef.value?.open();
};

// 关闭抽屉回调
const onFilterDrawerClose = () => {
  // 抽屉已关闭
};

// 选择器变更
const handleSelectorChange = (key: string, e: any, options: any[]) => {
  const index = e.detail.value;
  filterForm[key] = options[index];
};

// 日期选择
const handleDateChange = (key: string, e: any) => {
  filterForm[key] = e.detail.value;
};

// 日期范围选择
const handleDateRangeChange = (key: string, e: any) => {
  filterForm[key] = e;
  // 确保在日期改变时也恢复底部按钮
  handleDatePickerHide();
};

// App端选择器变更
const handleAppSelectorChange = (key: string, value: any) => {
  filterForm[key] = value;
};

// App端日期选择
const handleAppDateChange = (key: string, value: any) => {
  filterForm[key] = value;
};

// 日期选择器显示时切换抽屉模式
const handleDatePickerShow = () => {
  if (filterDrawerRef.value && filterDrawerRef.value.setDatePickerActive) {
    filterDrawerRef.value.setDatePickerActive(true);
  }
};

// 日期选择器隐藏时恢复抽屉模式
const handleDatePickerHide = () => {
  if (filterDrawerRef.value && filterDrawerRef.value.setDatePickerActive) {
    filterDrawerRef.value.setDatePickerActive(false);
  }

  // 添加延时恢复机制，确保在所有情况下都能恢复
  setTimeout(() => {
    if (filterDrawerRef.value && filterDrawerRef.value.setDatePickerActive) {
      filterDrawerRef.value.setDatePickerActive(false);
    }
  }, 100);
};

// 部门选择器显示时切换抽屉模式
const handleDepartmentPickerShow = () => {
  if (
    filterDrawerRef.value &&
    filterDrawerRef.value.setDepartmentPickerActive
  ) {
    filterDrawerRef.value.setDepartmentPickerActive(true);
  }
};

// 部门选择器隐藏时恢复抽屉模式
const handleDepartmentPickerHide = () => {
  if (
    filterDrawerRef.value &&
    filterDrawerRef.value.setDepartmentPickerActive
  ) {
    filterDrawerRef.value.setDepartmentPickerActive(false);
  }

  // 添加延时恢复机制，确保在所有情况下都能恢复
  setTimeout(() => {
    if (
      filterDrawerRef.value &&
      filterDrawerRef.value.setDepartmentPickerActive
    ) {
      filterDrawerRef.value.setDepartmentPickerActive(false);
    }
  }, 100);
};

// 时间选择
const handleTimeChange = (key: string, e: any) => {
  filterForm[key] = e.detail.value;
};

// 文本输入
const handleTextInput = (key: string, e: any) => {
  filterForm[key] = e.detail.value;
};

// 部门选择器变更
const handleDepartmentChange = (key: string, value: string) => {
  filterForm[key] = value;
};

// 重置筛选表单
const resetFilterForm = () => {
  Object.keys(filterForm).forEach((key) => {
    filterForm[key] = "";
  });

  // 重置后重新加载数据
  emits("filter", filterForm);
};

// 应用筛选条件
const applyFilter = () => {
  emits("filter", filterForm);
  // 模拟加载效果（只有在没有外部loading控制时才使用内部loading）
  if (!props.loading) {
    internalLoading.value = true;
    setTimeout(() => {
      internalLoading.value = false;
    }, 800);
  }
};

// 处理操作按钮点击
const handleAction = (actionKey: string, item: any) => {
  switch (actionKey) {
    case "view":
      handleView(item);
      break;
    case "edit":
      handleEdit(item);
      break;
    case "delete":
      handleDelete(item);
      break;
    default:
      emits("action", { actionKey, item });
  }
};

// 查看详情
const handleView = (item: any) => {
  emits("view", item);
  if (props.detailPagePath) {
    // 支持多种ID字段格式：ID（大写）、id（小写）
    const itemId = item.ID || item.id;

    // 记录导航时间，用于判断是否需要静默刷新
    lastNavigationTime.value = Date.now();

    uni.navigateTo({
      url: `${props.detailPagePath}?id=${itemId}`,
    });
  }
};

// 编辑
const handleEdit = (item: any) => {
  emits("edit", item);
  if (props.editPagePath) {
    // 支持多种ID字段格式：ID（大写）、id（小写）
    const itemId = item.ID || item.id;

    // 记录导航时间，用于判断是否需要静默刷新
    lastNavigationTime.value = Date.now();

    uni.navigateTo({
      url: `${props.editPagePath}?id=${itemId}`,
    });
  }
};

// 删除
const handleDelete = (item: any) => {
  uni.showModal({
    title: "删除提示",
    content: `确定删除吗？此操作不可撤销。`,
    success: async (res) => {
      if (res.confirm) {
        emits("delete", item);

        // 删除操作完成后，等待一小段时间再进行静默刷新
        if (props.enableSilentRefresh) {
          setTimeout(() => {
            performSilentRefresh();
          }, 500); // 等待500ms，确保删除操作完成
        }
      }
    },
  });
};

// 新增
const handleAdd = () => {
  emits("add");
  if (props.createPagePath) {
    // 记录导航时间，用于判断是否需要静默刷新
    lastNavigationTime.value = Date.now();

    uni.navigateTo({
      url: props.createPagePath,
    });
  }
};

// 页面加载
onMounted(() => {
  if (props.enableAutoRefresh) {
    // 只有在没有外部loading控制时才使用内部loading
    if (!props.loading) {
      internalLoading.value = true;
      setTimeout(() => {
        internalLoading.value = false;
        emits("refresh");
      }, 500);
    } else {
      // 如果有外部loading控制，直接触发refresh事件
      emits("refresh");
    }
  }
});

// 页面显示
uniOnShow(() => {
  // 优先检查静默刷新
  if (props.enableSilentRefresh) {
    checkSilentRefresh();
  } else if (props.enableAutoRefresh) {
    // 如果没有启用静默刷新，则使用原有的自动刷新逻辑
    // 只有在没有外部loading控制时才使用内部loading
    if (!props.loading) {
      internalLoading.value = true;
      setTimeout(() => {
        internalLoading.value = false;
        emits("refresh");
      }, 500);
    } else {
      // 如果有外部loading控制，直接触发refresh事件
      emits("refresh");
    }
  }
});

// 暴露方法给父组件
defineExpose({
  openFilterDrawer,
  performSilentRefresh,
  checkSilentRefresh,
});
</script>

<style lang="scss" scoped>
.list-container {
  display: flex;
  flex-direction: column;
  height: 100%;

  .search-section {
    padding: 16px 24px;
    flex-shrink: 0;

    .search-bar-container {
      display: flex;
      align-items: center;
      gap: 12px;

      .search-bar {
        flex: 1;
        height: 40px;
        background: #ffffff;
        border-radius: 20px;
        display: flex;
        align-items: center;
        padding: 0 16px;
        gap: 8px;

        .search-input {
          flex: 1;
          height: 100%;
          color: #666666;
          font-size: 14px;
          display: flex;
          align-items: center;
        }
      }

      .add-btn {
        height: 40px;
        padding: 0 16px;
        background: linear-gradient(135deg, #7579f5 0%, #9973f8 100%);
        border-radius: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 6px;
        box-shadow: 0 2px 8px rgba(107, 114, 242, 0.3);
        transition: transform 0.2s ease;

        .add-text {
          color: #ffffff;
          font-size: 14px;
          font-weight: 500;
        }

        &:active {
          transform: scale(0.95);
        }
      }
    }
  }

  .list-section {
    flex: 1;
    background: #ffffff;
    border-radius: 24px 24px 0 0;
    padding: 12px;
    overflow-y: auto;

    .loading-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      gap: 12px;

      .loading-text {
        color: #666;
        font-size: 14px;
      }
    }

    .list-container {
      /* 聊天列表样式 */
      .chat-item {
        display: flex;
        align-items: center;
        padding: 12px 16px;
        background: #ffffff;
        border-bottom: 1px solid #f0f0f0;
        transition: background-color 0.2s ease;
        width: 100%;
        box-sizing: border-box;

        &:active {
          background-color: #f8f9fa;
        }

        &:last-child {
          border-bottom: none;
        }

        .chat-avatar {
          margin-right: 12px;
          flex-shrink: 0;
          width: 44px; /* 固定宽度 */

          .default-chat-avatar {
            width: 44px;
            height: 44px;
            border-radius: 22px;
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            display: flex;
            align-items: center;
            justify-content: center;
          }
        }

        .chat-content {
          flex: 1;
          min-width: 0;
          max-width: calc(100% - 56px); /* 减去头像宽度和间距 */

          .chat-main {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 4px;
            width: 100%;

            .chat-title {
              flex: 1;
              color: #1a1a1a;
              font-size: 16px;
              line-height: 1.3;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              min-width: 0; /* 确保flex子元素可以收缩 */

              &.unread-title {
                font-weight: 600;
              }
            }

            .chat-time {
              color: #999;
              font-size: 12px;
              margin-left: 8px;
              flex-shrink: 0;
              white-space: nowrap;
            }
          }

          .chat-subtitle {
            color: #666;
            font-size: 14px;
            line-height: 1.3;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            width: 100%;
            display: block;
          }
        }
      }

      /* 原有卡片样式 */
      .data-card {
        background: #ffffff;
        border-radius: 16px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
        overflow: hidden;
        margin-bottom: 12px;

        &:last-child {
          margin-bottom: 0;
        }

        .card-header {
          display: flex;
          align-items: center;
          padding: 16px;
          gap: 12px;
          border-bottom: 1px solid #f5f5f5;

          &.no-avatar {
            /* 没有头像时的样式调整 - 移除gap，让内容靠左对齐 */
            gap: 0;

            .item-info {
              margin-left: 0;
            }
          }

          .item-avatar {
            width: 44px;
            height: 44px;
            border-radius: 22px;
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
          }

          .item-info {
            flex: 1;
            min-width: 0;

            .item-title {
              display: block;
              color: #1a1a1a;
              font-size: 16px;
              font-weight: 600;
              line-height: 1.3;
            }

            .item-subtitle {
              display: block;
              color: #666;
              font-size: 13px;
              line-height: 1.3;
            }
          }
        }

        .card-content {
          padding: 16px;

          .info-item {
            display: flex;
            margin-bottom: 4px;

            &:last-child {
              margin-bottom: 0;
            }

            .label {
              color: #666;
              font-size: 14px;
              min-width: 80px;
              max-width: 120px;
              flex-shrink: 0;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }

            .value {
              color: #333;
              font-size: 14px;
              flex: 1;
            }
          }
        }

        .card-footer {
          padding: 6px 16px;
          display: flex;
          align-items: center;
          justify-content: flex-end;
          border-top: 1px solid #f5f5f5;

          .action-buttons {
            display: flex;
            gap: 8px;

            .action-btn {
              display: flex;
              align-items: center;
              gap: 4px;
              padding: 6px 10px;
              border-radius: 4px;
              font-size: 12px;
              transition: all 0.2s ease;

              &:active {
                opacity: 0.7;
              }

              &.view-btn {
                color: #7881de;
                background-color: rgba(120, 129, 222, 0.1);
              }

              &.edit-btn {
                color: #4caf50;
                background-color: rgba(76, 175, 80, 0.1);
              }

              &.delete-btn {
                color: #ff5252;
                background-color: rgba(255, 82, 82, 0.1);
              }
            }
          }
        }
      }
    }

    .empty-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      gap: 12px;

      .empty-text {
        color: #666;
        font-size: 16px;
        font-weight: 500;
      }

      .empty-desc {
        color: #999;
        font-size: 14px;
      }
    }
  }
}

/* Picker样式 */
.form-picker {
  width: 100%;
  height: 36px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  box-sizing: border-box;
  background-color: #fff;

  .picker-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 100%;
    padding: 0 10px;

    .picker-text {
      font-size: 14px;
      color: #333;
      flex: 1;
      line-height: 36px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;

      &:empty::before {
        content: attr(placeholder);
        color: #999;
      }
    }
  }

  /* 兼容旧的 picker-value 样式 */
  .picker-value {
    font-size: 14px;
    color: #333;
    flex: 1;
    line-height: 36px;
    padding: 0 10px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

/* 输入框样式 */
.uni-input-wrapper {
  width: 100%;
  height: 36px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 10px;
  box-sizing: border-box;

  .uni-input {
    width: 100%;
    height: 100%;
    font-size: 14px;
    color: #333;
    border: none;
    outline: none;
    background: transparent;
  }
}

/* 徽章样式 */
.status-badge {
  display: inline-block;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
  white-space: nowrap;
  padding: 0 5px;
  /* 橙色主题 - 适用于待办、警告等 */
  &.badge-orange {
    background-color: #fef3c7;
    color: #d97706;
  }

  /* 绿色主题 - 适用于已完成、成功等 */
  &.badge-green {
    background-color: #dcfce7;
    color: #16a34a;
  }

  /* 蓝色主题 - 适用于协同、信息等 */
  &.badge-blue {
    background-color: #dbeafe;
    color: #1d4ed8;
  }

  /* 紫色主题 - 适用于个人提交、特殊状态等 */
  &.badge-purple {
    background-color: #f3e8ff;
    color: #7c3aed;
  }

  /* 红色主题 - 适用于紧急、错误等 */
  &.badge-red {
    background-color: #fee2e2;
    color: #dc2626;
  }

  /* 黄色主题 - 适用于高优先级、注意等 */
  &.badge-yellow {
    background-color: #fef3c7;
    color: #d97706;
  }

  /* 青色主题 - 适用于普通优先级等 */
  &.badge-cyan {
    background-color: #e0f2fe;
    color: #0369a1;
  }

  /* 灰色主题 - 适用于低优先级、默认状态等 */
  &.badge-gray {
    background-color: #f1f5f9;
    color: #64748b;
  }

  /* 默认样式 */
  &.badge-default {
    background-color: #f3f4f6;
    color: #6b7280;
  }
}

/* 日期范围选择器样式 */
.daterange-picker {
  width: 100%;

  :deep(.uni-datetime-picker) {
    width: 100%;
    height: 36px;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    background-color: #fff;

    .uni-datetime-picker-text {
      font-size: 14px;
      color: #333;
      padding: 0 10px;
      line-height: 36px;
    }

    .uni-datetime-picker-placeholder {
      color: #999;
    }
  }
}
</style>
